<template>
  <view class="content">
    <view class="order-container">
      <!-- 顶部tab栏 -->
      <view class="top-tabs">
        <u-tabs lineColor="#4182bb" lineWidth="64rpx" lineHeight="8rpx" activeStyle="color:#4182bb"
                ref="tabs" :is-scroll="true"
                inactiveStyle="#4E5969" :list="tabsList" :current="current" @click="tabsClick"
                :scrollable="true"></u-tabs>
      </view>

      <!-- 订单列表 -->
      <template v-if="dataList.length > 0">
        <scroll-view :scroll-top="0" scroll-y="true" class="scroll-content" :enable-passive="true"
                     :lower-threshold="30"
                     @scrolltolower="scrolltolower" :refresher-enabled="enablerefresh"
                     :refresher-triggered="triggered"
                     :refresher-threshold="100" refresher-default-style="white"
                     refresher-background="#F8F8F8"
                     @refresherpulling="onPulling" @refresherrefresh="onRefresh"
                     @refresherrestore="onRestore"
                     @refresherabort="onAbort">

          <!-- 订单列表项 -->
          <view class="order-item" v-for="order in dataList" :key="order.id">
            <!-- 订单头部信息 -->
            <view class="order-header">
              <view class="store-info" @click="goToShop(order)">
                <text class="store-name">{{ order.shopUser || '小店' }}</text>
              </view>
              <view class="order-status">
                <text class="status-text"
                      :class="'status-' + (order.status === 0 ? 'pending' : order.status === 1 ? 'completed' : order.status === 2 ? 'shipping' : order.status === 3 ? 'receiving' : order.status === 4 ? 'returned' : 'default')">
                  {{ order.status_dictText }}
                </text>
              </view>
            </view>

            <!-- 商品信息 -->
            <view class="product-info">
              <image class="product-image" :src="order.pic" mode="aspectFill"></image>
              <view class="product-details">
                <view class="product-name">{{ order.prodName || '商品名称' }}</view>
                <view class="product-spec">
                  <text class="spec-text">{{ order.remark || '--' }}</text>
                </view>
                <!--                <view class="product-features">-->

                <!--                </view>-->
              </view>
              <view class="product-price">
                <text class="price">￥{{ formatPrice(order.price) }}</text>
                <text class="quantity">x{{ order.num || 1 }}</text>
              </view>
            </view>

            <!-- 订单金额信息 -->
            <view class="order-amount">
              <view class="amount-item">
                <text class="amount-label">实付款</text>
                <text class="amount-value">￥{{ formatPrice(order.actualTotal) }}</text>
              </view>
            </view>

            <!-- 订单操作按钮 -->
            <view class="order-actions">
              <u-button
                  v-if="order.status === 0"
                  type="primary"
                  size="small"
                  @click="handlePay(order)"
                  :custom-style="{
                  marginRight: '20rpx',
                  backgroundColor: '#276AEE',
                  borderColor: '#276AEE',
                  borderRadius: '8rpx',
                  fontSize: '28rpx',
                  height: '64rpx',
                  minWidth: '120rpx'
                }"
              >
                立即支付
              </u-button>
              <u-button
                  v-if="order.status === 1 && order.isComm !== 1"
                  type="primary"
                  size="small"
                  @click="handleComment(order)"
                  :custom-style="{
                    marginRight: '20rpx',
                    backgroundColor: '#f59a23',
                    borderColor: '#f59a23',
                    color:'#ffffff',
                    borderRadius: '8rpx',
                    fontSize: '28rpx',
                    height: '64rpx',
                    minWidth: '120rpx'
                  }">
                立即评价
              </u-button>
              <u-button
                  v-if="order.status === 1"
                  type="warning"
                  size="small"
                  @click="handleRefundApply(order)"
                  :custom-style="{
                    marginRight: '20rpx',
                    backgroundColor: '#d20c32',
                    borderColor: '#d20c32',
                    color:'#ffffff',
                    borderRadius: '8rpx',
                    fontSize: '28rpx',
                    height: '64rpx',
                    minWidth: '120rpx'
                  }">
                申请退款
              </u-button>
              <u-button
                  v-if="order.status === 5"
                  type="warning"
                  size="small"
                  @click="handleSchedule(order)"
                  :custom-style="{
                    marginRight: '20rpx',
                    backgroundColor: '#d20c32',
                    borderColor: '#d20c32',
                    color:'#ffffff',
                    borderRadius: '8rpx',
                    fontSize: '28rpx',
                    height: '64rpx',
                    minWidth: '120rpx'
                  }">
                查看进度
              </u-button>
              <u-button
                  v-if="order.status === 3"
                  type="default"
                  size="small"
                  @click="handleConfirm(order)"
                  :custom-style="{
               marginRight: '20rpx',
                  backgroundColor: '#276AEE',
                  borderColor: '#276AEE',
                  borderRadius: '8rpx',
                    color:'#ffffff',
                  fontSize: '28rpx',
                  height: '64rpx',
                  minWidth: '120rpx'
                }"
              >
                确认收货
              </u-button>
              <u-button
                  type="default"
                  size="small"
                  @click="handleDetail(order)"
                  :custom-style="{
                  backgroundColor: '#f5f5f5',
                  borderColor: '#ddd',
                  color: '#666',
                  borderRadius: '8rpx',
                  fontSize: '28rpx',
                  height: '64rpx',
                  minWidth: '120rpx'
                }"
              >
                查看详情
              </u-button>
            </view>
          </view>
        </scroll-view>
      </template>

      <!-- 空状态 -->
      <view class="no-data" v-else>
        <image src="@/static/no-data.png" mode="widthFix"></image>
        <view class="no-data-text">暂无订单</view>
      </view>
    </view>
  </view>
</template>

<script>
// import shoptabbar from '@/pages/pagesMall/components/shoptabbar/shoptabbar.vue'
// import listItem from "../components/list/listMy.vue";
import {
  mapState,
  mapGetters
} from 'vuex'

export default {
  components: {
    // shoptabbar,
    // listItem
  },
  computed: {
    ...mapGetters(['userInfo']),
  },

  data() {
    return {
      statusBarHeight: 0,
      type: "4", // 固定为我的购买
      current: 0, // 当前tab默认选中值
      tabsList: [
        {
          name: '全部',
          status: ''
        },
        {
          name: '未支付',
          status: 0
        },
        {
          name: '待发货',
          status: 2

        }, {
          name: '待收货',
          status: 3
        },
        {
          name: '待退款',
          status: 5
        }, {
          name: '已退款',
          status: 4
        },
        {
          name: '已完成',
          status: 1
        }],
      dataList: [], // 订单数据
      pageNo: 1,
      pageSize: 10,
      total: 0,
      triggered: false,
      enablerefresh: true,
    };
  },
  // 注释掉onPageScroll使用scrolltolower 就这样吧
  // onPageScroll(e) {
  // 	//如果距顶部小于10，则允许下拉刷新
  // 	if (this.pageNo * this.pageSize < this.total) {
  // 		this.enablerefresh = true
  // 		console.log("允许下拉")
  // 		this.getOrderLists()
  // 	} else {
  // 		console.log("不允许下拉")
  // 		this.enablerefresh = false
  // 	}
  // },
  onLoad() {
    this.getSystemInfo()
    this.type = "4" // 固定为我的购买
    this.current = 0
  },
  async onShow() {
    this.pageNo = 1
    this.pageSize = 10
    this.dataList = []
    this.getOrderLists()
  },
  methods: {
    // 获取系统信息
    getSystemInfo() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0
    },

    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 获取我的购买订单列表
    getOrderLists() {
      let {
        openid
      } = uni.getStorageSync('openId')

      let data = {
        purchaseCardId: this.userInfo.id,
        purchaseOpenId: openid,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        status: this.tabsList[this.current].status,
      }

      this.$api.getOrderList(data).then(res => {
        if (res.success) {
          this.dataList = this.pageNo == 1 ? [...res.result.records] : [...this.dataList, ...res.result.records]
          this.total = res.result.total
          this.pageNo = res.result.current
          this.pageSize = res.result.size
          console.log('我的购买订单:', this.dataList)
        }
      }).catch(error => {
        console.error('获取订单失败:', error)
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
      })
    },
    // tab点击切换
    tabsClick({
                index
              }) {
      this.current = index
      console.log('切换tab:', this.current)
      this.pageNo = 1
      this.pageSize = 10
      this.dataList = []
      this.getOrderLists()
    },
    // 滚动到底部加载更多
    scrolltolower() {
      if (this.pageNo * this.pageSize < this.total) {
        this.enablerefresh = true
        console.log("加载更多订单")
        this.pageNo += 1
        this.getOrderLists()
      } else {
        console.log("没有更多订单了")
        this.enablerefresh = false
      }
    },
    // 下拉刷新
    onRefresh() {
      if (!this.triggered) {
        this.triggered = true;
        this.pageNo = 1;
        this.dataList = [];
        this.getOrderLists();

        setTimeout(() => {
          this.triggered = false;
        }, 500);
      }
    },
    // 下拉刷新控件被下拉
    onPulling(e) {
      // console.log("onpulling", e);
    },
    // 下拉刷新被复位
    onRestore() {
      this.triggered = false;
      console.log("onRestore");
    },
    // 下拉刷新被中止
    onAbort() {
      console.log("onAbort");
    },

    // 格式化价格
    formatPrice(price) {
      const num = Number(price || 0)
      return num.toFixed(2)
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}`
    },

    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已完成',
        2: '待发货',
        3: '待收货',
        4: '已退款',
        5: '待退款'
      }
      return statusMap[status] || '未知状态'
    },

    goToShop(item) {
      console.log('跳转商家', item)
      if (!item || !item.shopCardId) {
        uni.showToast({
          title: '商家信息不完整',
          icon: 'none'
        })
        return
      }
      uni.navigateTo({
        url: `/pagesMall/myShop/shopInfo?shopCardId=${item.shopCardId}`
      })
    },
    // 处理支付
    handlePay(order) {
      uni.showToast({
        title: '跳转支付页面',
        icon: 'none'
      })
      // TODO: 实现支付逻辑
    },
    // 去评价
    handleComment(order) {
      uni.navigateTo({
        url: `/pagesMall/myShop/appraise?id=${order.id}`
      })
    },
    // 申请退款
    handleRefundApply(order) {
      uni.navigateTo({
        url: `/pagesMall/myShop/refundApply?id=${order.id}`
      })
    },
    // 查看退款进度
    handleSchedule(order) {
      uni.navigateTo({
        url: `/pagesMall/myShop/schedule?id=${order.id}`
      })
    },
    // 处理确认收货
    handleConfirm(order) {
      let that = this
      uni.showModal({
        title: '确认收货',
        content: '确认已收到商品？',
        success: (r) => {
          if (r.confirm) {
            let params = {
              id: order.id
            }
            that.$api.addDeliveryFinish(params).then(res => {
              if (res.success) {
                uni.showToast({title: '已确认收货', icon: 'none'})
                that.getOrderLists()
              }
            })
          }
        }
      })
    },

    // 处理查看详情
    handleDetail(e) {
      uni.navigateTo({
        url: `/pagesMall/myOrder/bigGiftDetail?id=${e.id}&type=${this.type}&current=${this.current}&isCompany=false`
      })
    },
  },
};
</script>
<style>
page {
  background-color: #f8f8f8;
}
</style>
<style scoped lang="scss">
::v-deep.uni-scroll-view-refresh__spinner > circle {
  color: #ff7000 !important;
}

::v-deep.uni-scroll-view-refresh-inner > svg {
  fill: #ff7000 !important;
}

.content {
  width: 100vw;
  height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.status-bar {
  background-color: #fff;
}

.custom-navbar {
  background-color: #fff;
  border-bottom: 2rpx solid #ebeef5;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
}

.navbar-left {
  width: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 600;
  color: #303133;
}

.navbar-right {
  width: 80rpx;
}

.order-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 0;
}

.top-tabs {
  background-color: #fff;
  border-bottom: 2rpx solid #ebeef5;
  padding: 20rpx 0;
  z-index: 10;
}

.scroll-content {
  flex: 1;
  height: 0;
  //padding: 20rpx;
}


.no-data {
  width: 100%;
  text-align: center;
  font-size: 32rpx;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 500;
  color: #4e5969;
  padding: 120rpx 40rpx;
  margin: 0 auto;

  image {
    width: 240rpx;
    height: 210rpx;
    margin: auto;
  }

  .no-data-text {
    margin-top: 40rpx;
  }
}

/* 订单列表样式 */
.order-item {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  margin: 16rpx 20rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f2f5;
}

.store-info {
  flex: 1;
}

.store-name {
  font-size: 28rpx;
  color: #303133;
  font-weight: 500;
}

.order-status {
  flex-shrink: 0;
}

.status-text {
  font-size: 28rpx;
  font-weight: 600;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
}

.status-pending {
  color: #f59a23;
  background: #fff2e8;
}

.status-completed {
  color: #52c41a;
  background: #f6ffed;
}

.status-shipping {
  color: #1890ff;
  background: #e6f7ff;
}

.status-receiving {
  color: #fa8c16;
  background: #fff7e6;
}

.status-returned {
  color: #f5222d;
  background: #fff1f0;
}

.status-default {
  color: #8c8c8c;
  background: #f5f5f5;
}

.product-info {
  display: flex;
  margin-bottom: 20rpx;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  background: #f5f5f5;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  //justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  color: #303133;
  font-weight: 500;
  line-height: 1.4;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
}

.product-spec {
  margin-bottom: 8rpx;
}

.spec-text {
  font-size: 24rpx;
  color: #666;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}

.product-features {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
}

.feature-tag {
  font-size: 20rpx;
  color: #276AEE;
  background: #fff2e8;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  border: 1rpx solid #276AEE;
}

.product-price {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  min-width: 120rpx;
}

.price {
  font-size: 28rpx;
  color: #ff4d4f;
  font-weight: 600;
  margin-bottom: 4rpx;
}

.quantity {
  font-size: 24rpx;
  color: #999;
}

.order-amount {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid #f0f2f5;
}

.amount-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.amount-label {
  font-size: 26rpx;
  color: #666;
}

.amount-value {
  font-size: 28rpx;
  color: #ff4d4f;
  font-weight: 600;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 16rpx;
}
</style>
